//
//  ZGWPeopleReportViewController.m
//  1gene
//
//  Created by 张国文 on 16/7/5.
//  Copyright © 2016年 1jiyin. All rights reserved.
//

#import "ZGWPeopleReportViewController.h"
#import "ZGWPeopleAllReportModel.h"
#import "JianKangDaoAnReportTableViewCell.h"
#import "ShiLiBaoGaoViewController.h"

#define kCurrentUserToken [[NSUserDefaults standardUserDefaults]objectForKey:@"token"]

@interface ZGWPeopleReportViewController ()<UITableViewDataSource, UITableViewDelegate>


@property (nonatomic, strong) NSTimer *myTimer; // 检查请求是否超时
@property (nonatomic, assign) NSInteger numberOfTime; // 存储请求时间
@property (nonatomic, strong) UITableView *reportTableView; // 报告tableView
@property (nonatomic, strong) NSMutableArray *reportArray; // 报告数组

@property (nonatomic, strong) UIButton *deleteSamplePeople; // 删除采样人

@end

@implementation ZGWPeopleReportViewController

- (void)viewWillAppear:(BOOL)animated
{
     self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:22]};
    [super viewWillAppear:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
    [self.myTimer invalidate];
    self.numberOfTime = 0;
    [super viewWillDisappear:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    // navi的修改
    [self changeNavigation];
    // 检查网络并建立数据源
    [self searchNetAndAddData];
}

// navi的修改
- (void)changeNavigation
{
    self.navigationItem.title = [NSString stringWithFormat:@"%@健康报告", self.sampleUserName];
    UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    leftImageView.image = [UIImage imageNamed:@"houtui"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftImageView];
    UITapGestureRecognizer *leftTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lastPage:)];
    [leftImageView addGestureRecognizer:leftTapGes];
    
    if (self.isMine == YES) {
        // 说明是自己的健康档案
    } else if (self.isMine == NO) {
        // 说明是其他人的健康档案
        // 删除采样人
        self.deleteSamplePeople = [UIButton buttonWithType:UIButtonTypeSystem];
        self.deleteSamplePeople.frame = CGRectMake(0, 0, 100, 23);
        [self.deleteSamplePeople setTitle:@"删除采样人" forState:UIControlStateNormal];
        [self.deleteSamplePeople setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.deleteSamplePeople addTarget:self action:@selector(deletePeople:) forControlEvents:UIControlEventTouchUpInside];
        self.deleteSamplePeople.titleLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:k16Big];
        self.deleteSamplePeople.layer.borderWidth = 1 * kAdjustParamater;
        self.deleteSamplePeople.layer.borderColor = [[UIColor whiteColor] CGColor];
        self.deleteSamplePeople.layer.cornerRadius = 6 * kAdjustParamater;
        self.deleteSamplePeople.layer.masksToBounds = YES;
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.deleteSamplePeople];
    }
    
    
}

#pragma mark - 返回上一页面
- (void)lastPage:(UITapGestureRecognizer *)tapGes
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 删除采样人
- (void)deletePeople:(UIButton *)button
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您确定要删除该采样人么？删除以后该采样人下的所有报告将会转移到我的报告下" preferredStyle:UIAlertControllerStyleAlert];
    // 修改标题颜色
    NSMutableAttributedString *titleString = [[NSMutableAttributedString alloc] initWithString:@"温馨提示"];
    [titleString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 4)];
    [titleString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, 4)];
    [alertVC setValue:titleString forKey:@"attributedTitle"];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:sureAction];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

#pragma mark - 检查网络并建立数据源
- (void)searchNetAndAddData
{
    if ([[[NetStatusHandle shareHandle] getNetStatus] isEqualToString:@"YES"]) {
        // 说明有网络
        // 建立数据源
        [self addData];
        
            // 说明不是示例报告
            // 建立计时器，计算是否超时
            self.myTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(goTimeOnJianKangDangAnReport:) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:self.myTimer forMode:NSRunLoopCommonModes];
            self.numberOfTime = 0;
            // 开始动画
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
        
        
        
        
    } else {
        NSLog(@"没有网络");
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kNoNetNoRefresh ToView:self];
    }
}

#pragma mark - 添加数据
- (void)addData
{
    // 采样人的所有报告
    NSString *allReportUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWGetAllReportOfCaiYangRen, kCurrentUserToken];
    NSDictionary *paramaterIDic = @{@"sampleuser_id":self.sampleuser_id};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:allReportUrl parameters:paramaterIDic success:^(NSURLSessionDataTask *task, id responseObject) {
        // 将计时器置为0
        self.numberOfTime = 0;
        [self.myTimer invalidate];
        // 结束动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        if (!responseObject) {
            return;
        }
        NSArray *reportsArray = [responseObject valueForKey:@"reports"];
        self.reportArray = [NSMutableArray array];
        for (int i = 0; i < reportsArray.count; i++) {
            NSDictionary *tempDic = reportsArray[i];
            ZGWPeopleAllReportModel *reportModel = [[ZGWPeopleAllReportModel alloc] init];
            [reportModel setValuesForKeysWithDictionary:tempDic];
            [reportModel setValue:[NSString stringWithFormat:@"报告%d", i + 1] forKey:@"reportNumber"];
            [self.reportArray addObject:reportModel];
        }
        if (self.reportArray.count == 0) {
            // 说明没有报告
            [self addNoReportView];
        } else {
            // 布局
            [self addMySubview];
        }
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kHuoQuDataShiBaiNoRefresh ToView:self];
        // 暂停计时器
        [self.myTimer invalidate];
        self.numberOfTime = 0;
    }];
}

#pragma mark - 提示该用户当前没有健康档案
- (void)addNoReportView
{
    // 说明没有参考文献
    UILabel *alertLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 250 * kAdjustParamater, kScreenWidth, 30 * kAdjustParamater)];
    alertLabel.text = @"该用户目前没有健康报告";
    alertLabel.textAlignment = NSTextAlignmentCenter;
    alertLabel.textColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    alertLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:25 * kAdjustParamater];
    [self.view addSubview:alertLabel];
}

#pragma mark - 计时器方法
- (void)goTimeOnJianKangDangAnReport:(NSTimer *)timer
{
    self.numberOfTime++;
    NSLog(@"用户报告时间= %ld", self.numberOfTime);
    if (self.numberOfTime > kZGWQingQiuChaoShi) {
        NSLog(@"用户报告请求超时");
        self.numberOfTime = 0;
        [self.myTimer invalidate];
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kQingQiuChaoShiNoReFresh ToView:self];
    }
}

#pragma mark - 布局
- (void)addMySubview
{
    self.reportTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    self.reportTableView.backgroundColor = [UIColor whiteColor];
    self.reportTableView.dataSource = self;
    self.reportTableView.delegate = self;
    [self.view addSubview:_reportTableView];
}

#pragma mark - tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.reportArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *identifier = @"reportCell";
    JianKangDaoAnReportTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[JianKangDaoAnReportTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.reportArray.count > indexPath.row) {
        ZGWPeopleAllReportModel *reportModel = self.reportArray[indexPath.row];
        cell.model = reportModel;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70 * kAdjustParamater;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShiLiBaoGaoViewController *shiLiBaoGaoVC = [[ShiLiBaoGaoViewController alloc] init];
    if (self.reportArray.count > indexPath.row) {
        ZGWPeopleAllReportModel *reportModel = self.reportArray[indexPath.row];
        shiLiBaoGaoVC.report_id =  [NSString stringWithFormat:@"%@", reportModel.reportID];
    }
    shiLiBaoGaoVC.isShiLiBaoGaoFormServer = NO;
    shiLiBaoGaoVC.userName = self.sampleUserName;
    [self.navigationController pushViewController:shiLiBaoGaoVC animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
